package cn.maihe.elg.operation.service.order;

import cn.maihe.elg.operation.repository.entity.AcceptOrderInfoDO;
import cn.maihe.elg.operation.repository.entity.SpdBankNotice;
import cn.maihe.elg.operation.repository.entity.SpdBankNoticeCondition;
import cn.maihe.elg.operation.service.BaseDaoService;
import cn.maihe.elg.operation.utils.CreateGuaranteeUtil;
import cn.maihe.elg.operation.utils.ElgLogger;
import cn.maihe.framework.starter.base.sql.PageBo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Description
 * @Author WJH
 * @Date 2021/11/23
 */
@Service
@Slf4j
public class SpdBankNoticeService extends BaseDaoService<SpdBankNotice> {

    private List<String> coreSerNoList = new ArrayList<>();

    public void initCoreNo() {
        Map<String, Object> map = new HashMap<>();
        int curPage = 1;
        PageBo<String> pageBo = this.selectPageBySql("selectCoreSerNoList", "selectCoreSerNoCount", map, curPage, 1000);
        if (pageBo.getTotal() > 0) {
            coreSerNoList = new ArrayList<>((int) pageBo.getTotal());
        }

        if (!CollectionUtils.isEmpty(pageBo.getList())) {
            coreSerNoList.addAll(pageBo.getList());
        }
        //其他页查询
        for (int nextPage = curPage + 1; nextPage <= pageBo.getPages(); nextPage++) {
            PageBo<String> nextPageBo = this.selectPageBySql("selectCoreSerNoList", "selectCoreSerNoCount", map, nextPage, 1000);
            if (!CollectionUtils.isEmpty(nextPageBo.getList())) {
                coreSerNoList.addAll(nextPageBo.getList());
            }
        }
        // 库表数据太多提示替换方案
        if (coreSerNoList.size() > 200000) {
            ElgLogger.warn(log, l -> l.warn("银企直连库表记录数超过20W条记录，请及时变更核心流水号判重机制"));
        }
    }

    public boolean existsCoreSerNo(String coreSerNo) {
        return coreSerNoList.contains(coreSerNo);
    }


    public SpdBankNotice saveOrUpdate(SpdBankNotice spdBankNotice) {
        String coreSerNo = spdBankNotice.getCoreSerNo();
        if (StringUtils.isNotBlank(coreSerNo)) {
            SpdBankNotice dbSpdBankNotice = getSpdBankNoticeByCoreSerNo(coreSerNo);
            if (dbSpdBankNotice == null) {
                this.insert(spdBankNotice);
                coreSerNoList.add(coreSerNo);
                return spdBankNotice;
            } else {
                return dbSpdBankNotice;
            }
        }
        return null;
    }


//    public SpdBankNotice saveOrUpdate(SpdBankNoticeReqHead postBeanHead, SpdBankNoticeReqA1008Body data) {
//        String coreSerNo = data.getCoreSerNo();
//        if (StringUtils.isNotBlank(coreSerNo)) {
//            SpdBankNotice spdBankNotice = getSpdBankNoticeByCoreSerNo(coreSerNo);
//            if (spdBankNotice == null) {
//                spdBankNotice = build(postBeanHead, data);
//                this.insert(spdBankNotice);
//                coreSerNoList.add(coreSerNo);
//            }
//            return spdBankNotice;
//        }
//        return null;
//    }
//
//    private SpdBankNotice build(SpdBankNoticeReqHead postBeanHead, SpdBankNoticeReqA1008Body data) {
//        SpdBankNotice spdBankNotice = new SpdBankNotice();
//        spdBankNotice.setId(IdGenerate.getId());
//        spdBankNotice.setNoticeDate(postBeanHead.getNoticeDate());
//        spdBankNotice.setNoticeTime(postBeanHead.getNoticeTime());
//        spdBankNotice.setNoticeType(postBeanHead.getNoticeType());
//        spdBankNotice.setNoticeSerNo(postBeanHead.getNoticeSerNo());
//        spdBankNotice.setZoneCode(data.getZoneCode());
//        spdBankNotice.setSecuNo(data.getSecuNo());
//        spdBankNotice.setSecuName(data.getSecuName());
//        spdBankNotice.setMerchNo(data.getMerchNo());
//        spdBankNotice.setMerchName(data.getMerchName());
//        spdBankNotice.setParentAcctNo(data.getParentAcctNo());
//        spdBankNotice.setParentAcctName(data.getParentAcctName());
//        spdBankNotice.setDepSerNo(data.getDepSerNo());
//        spdBankNotice.setCoreSerNo(data.getCoreSerNo());
//        spdBankNotice.setCoreTransDate(data.getCoreTransDate());
//        spdBankNotice.setCoreTransTime(data.getCoreTransTime());
//        spdBankNotice.setTransDate(data.getTransDate());
//        spdBankNotice.setTransTime(data.getTransTime());
//        spdBankNotice.setBusiType(data.getBusiType());
//        spdBankNotice.setTransAmt(data.getTransAmt());
//        spdBankNotice.setAcctBankName(data.getAcctBankName());
//        spdBankNotice.setAcctBankNo(data.getAcctBankNo());
//        spdBankNotice.setAcctName(data.getAcctName());
//        spdBankNotice.setAcctNo(data.getAcctNo());
//        spdBankNotice.setAttach(data.getAttach());
//        spdBankNotice.setRemark1(data.getRemark1());
//        spdBankNotice.setRemark2(data.getRemark2());
//        spdBankNotice.setRemark3(data.getRemark3());
//
//        return spdBankNotice;
//
//
//    }

    public SpdBankNotice getSpdBankNoticeByCoreSerNo(String coreSerNo) {
        SpdBankNoticeCondition condition = SpdBankNoticeCondition.builder().andCoreSerNoEq(coreSerNo);
        return this.selectOne(condition.build());
    }

    public SpdBankNotice selectMatchPayInfoAndSectionCode(String payerAcctNo, String payeeAcctNo, Long guaranteeFee,
                                                          String projectCode, AcceptOrderInfoDO acceptOrderInfo) {
        if (StringUtils.isBlank(payeeAcctNo) || guaranteeFee == null || Objects.isNull(acceptOrderInfo)) {
            ElgLogger.error(log, l -> l.error("payeeAcctNo is null or guaranteeFee is null or acceptOrderInfo is null"));
            return null;
        }

        // 投保企业基本户银行卡号（付款方）匹配标识
        boolean payerAcctNoMatchFlag = true;
        if(CreateGuaranteeUtil.isXiAn(acceptOrderInfo.getAcceptOrderNo(),acceptOrderInfo.getClientId())){
            ElgLogger.info(log, l -> l.info("西安地区不需要匹配基本户,受理订单号：{};客户端ID：{}" , acceptOrderInfo.getAcceptOrderNo(),acceptOrderInfo.getClientId()));
            payerAcctNoMatchFlag = false;
        }

        Map<String, Object> params = new HashMap<>();
        if(payerAcctNoMatchFlag){
            if (StringUtils.isBlank(payerAcctNo)) {
                return null;
            }
            params.put("payerAcctNo", payerAcctNo);
        }
        params.put("payeeAcctNo", payeeAcctNo);
        params.put("guaranteeFee", guaranteeFee);

        if(CreateGuaranteeUtil.isMeiShanByAcceptOrderNo(acceptOrderInfo.getAcceptOrderNo())){
            params.put("subAccount", acceptOrderInfo.getSubAccount());
        }else {
            params.put("projectCode", StringUtils.isBlank(projectCode) ? "projectCode" : projectCode);

            if(CreateGuaranteeUtil.isGuoGuNonSuiXing(acceptOrderInfo.getAcceptOrderNo(), acceptOrderInfo.getClientId())){
                params.put("acceptOrderNo", acceptOrderInfo.getAcceptOrderNo());
            }
        }
        return this.selectOneBySql("selectMatchPayInfoAndSectionCode", params);
    }

    /**
     * 查询匹配的支付流水
     *
     * @param payerAcctNo  付款方账号
     * @param payeeAcctNo  收款方账号
     * @param guaranteeFee 保费金额
     * @param subAccount 记账子单元编号
     * @return List<SpdBankNotice>
     * @author Alan
     * @date 2023/10/18 16:44
     */
    public List<SpdBankNotice> selectMatchPayInfos(String payerAcctNo, String payeeAcctNo, Long guaranteeFee,String subAccount) {
        if (StringUtils.isAnyBlank(payerAcctNo, payeeAcctNo) || guaranteeFee == null) {
            return null;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("payerAcctNo", payerAcctNo);
        params.put("payeeAcctNo", payeeAcctNo);
        params.put("guaranteeFee", guaranteeFee);
        if(StringUtils.isNotBlank(subAccount)){
            params.put("subAccount", subAccount);
        }
        return this.selectListBySql("selectMatchPayInfos", params);
    }

}
